import * as THREE from 'three'
// 精灵标签--标签始终面向相机
export const createPoint = (config, threeInfo) => {
  const { name, position, scopeCode, scopeLevel, isClick, perData } = config
  let { group, quCode } = threeInfo
  let baseW = window.innerWidth || 1920
  let baseH = window.innerHeight || 1080

  // 如果perData为 空格、空或者为 null 则缩小图片高度
  if (!perData || perData === ' ') {
    baseH = baseH * 0.5
  } else {
    baseH = baseH * 0.7
  }

  let adjustedBaseH = baseH
  if (window.innerHeight <= 768) {
    adjustedBaseH -= 50
  } else if (window.innerWidth <= 1366 && window.innerHeight === 1080) {
    adjustedBaseH -= 200
  }

  const texture = new THREE.CanvasTexture(getCanvasFont(name, adjustedBaseH))

  const fontMesh = new THREE.Sprite(
    new THREE.SpriteMaterial({
      transparent: true,
      opacity: 1,
      map: texture,
    })
  )
  fontMesh.name = name
  fontMesh['scopeCode'] = scopeCode
  fontMesh['scopeLevel'] = scopeLevel
  fontMesh['isClick'] = isClick

  const r = window.innerWidth <= 1366 ? 100 : 200
  fontMesh.scale.x = baseW / r
  fontMesh.scale.y = adjustedBaseH / r

  const offset = 2
  fontMesh.position
    .copy(position)
    .add(new THREE.Vector3(offset, offset, offset))

  group.add(fontMesh)

  // 创建 canvas 图片标签
  function getCanvasFont(name, baseH) {
    const fontColor = quCode.includes(scopeCode) ? '#f6e229' : '#ffffff'
    const w = baseW
    const h = baseH

    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    canvas.width = w
    canvas.height = h

    ctx.fillStyle = '#0c3f8291'
    ctx.fillRect(0, 0, w, h)

    ctx.lineWidth = 10
    ctx.strokeStyle = fontColor
    ctx.strokeRect(0, 0, w, h)

    ctx.fillStyle = fontColor
    ctx.font = `bold ${w / 6}px Arial`
    // 如果文案长度大于图片尺寸则缩小字体
    if (ctx.measureText(name).width > w) {
      ctx.font = `bold ${w / 8}px Arial`
    }
    // 如果perData为 “ ” 或者为 null 文字上下居中
    if (!perData || perData === ' ') {
      ctx.textBaseline = 'middle'
      ctx.font = `bold ${w / 8}px Arial`
    }
    ctx.textAlign = 'center'
    ctx.shadowColor = '#000'
    if (perData && perData !== ' ') {
      ctx.fillText(name, w / 2, h / 2.2)
      ctx.fillText(perData, w / 2, (h / 2) * 1.8)
    } else {
      ctx.fillText(name, w / 2, h / 2)
    }

    return canvas
  }
}
